<template>
  <a-modal
    v-model="modalVisible"
    :title="mode === 'select' ? '选择人员' : '适用范围-粘贴选择'"
    :width="mode === 'select' ? '1200px' : '800px'"
  >
    <div class="flex">
      <template v-if="mode === 'select'">
        <div style="width: 290px">
          <div class="flex-center">
            <span>筛选条件：</span>
            <a-input v-model="nameOrPhoneOrIdCard" placeholder="员工姓名/身份证号/手机号" style="width: 200px" />
          </div>
          <div class="flex-center mt16">
            <span>用工单位：</span>
            <a-select
              v-model="companyId"
              :options="companyLst"
              placeholder="请选择"
              :filterOption="filterOption"
              show-search
              style="width: 200px"
            />
          </div>
        </div>
        <div style="width: 630px">
          <a-table
            :columns="columns"
            :dataSource="currentEmpLst"
            :loading="loading"
            rowKey="id"
            size="small"
            :pagination="pagination"
            :rowSelection="{
              selectedRowKeys: selectedRowKeys,
              onChange: onSelectChange
            }"
            @change="handleTableChange"
          ></a-table>
        </div>
      </template>
      <div v-else style="width: 520px">
        <div class="pv8 ph12 mb16" style="background: #f7f7f7">
          <div class="fs16 tc-l1">温馨提示</div>
          <div class="tc-l3 mt12">1.在文本框内输入或批量粘贴企业在职员工身份证号，便可识别添加。</div>
          <div class="tc-l3 mt4">2.非企业员工无法识别。</div>
          <div class="tc-l3 mt4">3.支持以换行、回车、空格等符号隔开的身份证号识别。</div>
        </div>
        <a-textarea v-model="idCards" placeholder="请输入或粘贴员工身份证号" :rows="10" :autoSize="false" style="resize: none"></a-textarea>
        <div class="ta-right mt12">
          <a-space :size="16">
            <a-button @click="doReset">重置</a-button>
            <a-button type="primary" @click="doDistinguish">识别</a-button>
          </a-space>
        </div>
      </div>
      <div class="ml12 pl12 border-left">
        <div class="fs12 mb12">
          已选择人员<span class="tc-theme"> {{ selectedEmpLst.length }} </span>人
        </div>
        <div class="overflow-y-auto" style="max-height: 450px">
          <div v-for="item in selectedEmpLst" :key="item.id" class="flex-center-between mb8">
            <div class="ellipsis" style="width: 180px">
              <a-tooltip :title="`${item.name} ${item.phone} ${item.idCard}`">{{ item.name }} {{ item.phone }}</a-tooltip>
            </div>
            <a-icon
              type="close-circle"
              theme="filled"
              class="fs16 pointer ml12"
              style="color: rgba(215, 215, 215, 1); flex-shrink: 0"
              @click="delFromSelectedLst(item.id)"
            />
          </div>
        </div>
      </div>
    </div>
    <div slot="footer" class="flex-center-between">
      <a-button v-if="mode === 'select'" type="link" @click="mode = 'input'">粘贴选择</a-button>
      <a-button v-else type="link" @click="mode = 'select'">条件选择</a-button>
      <a-space :size="16">
        <a-button @click="doCancel">取消</a-button>
        <a-button type="primary" @click="doConfirm">确定</a-button>
      </a-space>
    </div>
  </a-modal>
</template>
<script>
import { mapState } from "vuex";
import { filterEmptyValue } from "@/utils/tools";
const columns = [
  {
    title: "姓名",
    dataIndex: "name",
    width: 100,
    ellipsis: true
  },
  {
    title: "手机号",
    dataIndex: "phone",
    width: 120,
    ellipsis: true
  },
  {
    title: "身份证号",
    dataIndex: "idCard",
    width: 180,
    ellipsis: true
  },
  {
    title: "用工单位",
    dataIndex: "companyName",
    width: 150,
    ellipsis: true
  }
];
export default {
  name: "",
  components: {},
  mixins: [],
  props: {
    value: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      columns,
      idCards: "",
      nameOrPhoneOrIdCard: "",
      companyId: undefined,
      pagination: {
        pageSize: 10,
        total: 0,
        size: "small",
        current: 1,
        showTotal: (total) => `共 ${total} 条`
      },
      currentEmpLst: [],
      currentEmpLstKeys: [],
      currentEmpLstDict: {},
      modalVisible: false,
      selectedRowKeys: [],
      loading: false,
      selectedEmpLst: [],
      mode: "select" // input
    };
  },
  computed: {
    ...mapState(["hr"]),
    companyList() {
      return this.hr.companyList;
    },
    companyLst() {
      return this.companyList.map((item) => ({
        value: item.id,
        label: item.name
      }));
    }
  },
  watch: {
    value: {
      handler(newVal) {
        this.mode = "select";
        this.idCards = "";
        this.modalVisible = newVal;
      },
      immediate: true
    },
    modalVisible() {
      this.$emit("input", this.modalVisible);
      this.$emit("change", this.modalVisible);
      if (this.modalVisible) {
        this.clear();
      }
    },
    nameOrPhoneOrIdCard() {
      this.loadEmpLst();
    },
    companyId(newVal) {
      if (newVal) {
        this.loadEmpLst();
      }
    }
  },
  created() {},
  mounted() {},
  methods: {
    doReset() {
      this.idCards = "";
    },
    doDistinguish() {
      if (!this.idCards) {
        return false;
      }
      this.$request({
        url: `/hr/api/v1/empInfos/selectSiteEmpStickupSelect`,
        method: "post",
        data: this.idCards.replaceAll(" ", ",").replaceAll("\r\n", ",").replaceAll("\n", ",").replaceAll("\t", ",").split(",")
      })
        .then((res) => {
          this.selectedEmpLst = [...res.data.empInfoVOList, ...this.selectedEmpLst];
        })
        .catch((err) => {
          console.log("empInfos/selectSiteEmpStickupSelect", err);
        });
    },
    clear() {
      this.nameOrPhoneOrIdCard = "";
      this.companyId = undefined;
      this.pagination.current = 1;
      this.pagination.total = 0;
      this.currentEmpLst = [];
      this.currentEmpLstKeys = [];
      this.currentEmpLstDict = {};
      this.selectedRowKeys = [];
      this.selectedEmpLst = [];
    },
    doCancel() {
      this.$emit("cancel");
      this.modalVisible = false;
    },
    doConfirm() {
      this.$emit("confirm", [...this.selectedEmpLst]);
      this.modalVisible = false;
    },
    delFromSelectedLst(key) {
      this.updateSelectedEmpLst(null, key);
    },
    updateSelectedEmpLst(keys = null, delKey) {
      let otherItems = [];
      let currentItems = [];
      let currentKeys = [];
      for (let i = 0; i < this.selectedEmpLst.length; i++) {
        const item = this.selectedEmpLst[i];
        if (this.currentEmpLstKeys.includes(item.id)) {
          if (keys) {
            if (keys.includes(item.id)) {
              currentItems.push(item);
              currentKeys.push(item.id);
            }
          } else {
            currentItems.push(item);
            currentKeys.push(item.id);
          }
        } else {
          otherItems.push(item);
        }
      }
      // 上面只是处理全部选中，有可能新选中的不在其中，需要补充进去
      if (keys) {
        if (keys.length > currentKeys.length) {
          const leftKeys = keys.filter((key) => !currentKeys.includes(key));
          for (let i = 0; i < leftKeys.length; i++) {
            currentItems.push(this.currentEmpLstDict[leftKeys[i]]);
          }
        }
        currentKeys = currentItems.map((item) => item.id);
      }
      if (delKey) {
        if (currentKeys.includes(delKey)) {
          currentKeys = currentKeys.filter((key) => key !== delKey);
          currentItems = currentItems.filter((item) => delKey !== item.id);
        } else {
          otherItems = otherItems.filter((item) => delKey !== item.id);
        }
      }
      this.selectedRowKeys = currentKeys;
      this.selectedEmpLst = [...currentItems, ...otherItems];
    },
    onSelectChange(keys) {
      this.updateSelectedEmpLst(keys);
    },
    handleTableChange(pagination) {
      this.pagination.current = pagination.current;
      this.pagination.pageSize = pagination.pageSize;
      this.loadEmpLst();
    },
    loadEmpLst() {
      this.loading = true;
      this.$request({
        url: `/hr/api/v1/empInfos/selectSiteEmp`,
        params: filterEmptyValue({
          nameOrPhoneOrIdCard: this.nameOrPhoneOrIdCard,
          companyId: this.companyId,
          pageNo: this.pagination.current,
          pageSize: this.pagination.pageSize
        })
      })
        .then((res) => {
          this.currentEmpLst = res.data.entities;

          const tempArr = [];
          const tempObj = {};
          for (let i = 0; i < this.currentEmpLst.length; i++) {
            const item = this.currentEmpLst[i];
            tempArr.push(item.id);
            tempObj[item.id] = item;
          }
          this.currentEmpLstKeys = tempArr;
          this.currentEmpLstDict = tempObj;
          this.updateSelectedEmpLst();

          this.pagination.total = res.data.entityCount;
          this.loading = false;
        })
        .catch((err) => {
          console.log("empInfos/selectSiteEmp", err);
          this.loading = false;
        });
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0;
    }
  }
};
</script>
<style lang="scss"></style>
